import 'dart:convert';

import 'package:flutter/material.dart';
import '../person/Login.dart';

import '../../YColors.dart';
import '../MyRefreshTest.dart';
import '../order/TodoTask.dart';
import '../order/HistoryTask.dart';
import '../order/FinishTask.dart';
import '../order/LaunchTask.dart';
import '../../util/HttpUtil.dart';
import '../../util/Storage.dart';
import '../../util/ToastUtils.dart';
import '../../util/LogUtil.dart';
import '../../global/Global.dart';
import '../../global/GlobalUrl.dart';

class DynamicOrderPage extends StatefulWidget {
  DynamicOrderPage({Key key}) : super(key: key);

  _DynamicOrderPageState createState() => _DynamicOrderPageState();
}

class _DynamicOrderPageState extends State<DynamicOrderPage>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  List dataList = [];
  List tabList = [];

  @override
  void initState() {
    // 生命周期函数
    // TODO: implement initState
    super.initState();
    _tabController = new TabController(
      vsync: this,
      length: 6,
    );

    /*
    * 监听状态的变化
    * */
    _tabController.addListener(() {
      print('点击了${_tabController.index}');
//      print(_tabController.index);
//      setState(() {
//
//      });
    });

    initHttpData();
  }

  @override
  void dispose() {
    // 生命周期函数
    // TODO: implement dispose
    super.dispose();
    print('dispose');
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: tabList != null ? tabList.length : 0,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xffffffff),
          title: Row(
            children: <Widget>[
              Expanded(
                child: TabBar(
                  isScrollable: true,
                  // 可以滑动
                  indicatorColor: Colors.green,
                  // 指示器验收
                  labelColor: Colors.green,
                  // 选中 label 颜色
                  unselectedLabelColor: YColors.b,
                  // 选中 label 颜色
//            指示器大小计算方式，TabBarIndicatorSize.label 跟文
//           字等宽,TabBarIndicatorSize.tab 跟每个 tab 等宽
//                  indicatorSize: TabBarIndicatorSize.label,

                  tabs: setTabWidget(),
//                  tabs: <Widget>[
//                    Tab(
//                      text: "待办任务",
//                    ),
//                    Tab(
//                      text: "历史任务",
//                    ),
//                    Tab(
//                      text: "办结任务",
//                    ),
//                    Tab(
//                      text: "我发起的流程",
//                    ),
//                  ],
                ),
              )
            ],
          ),
          centerTitle: true,
        ),
        body: TabBarView(
          children: setContentViewWidget(),
//          children: <Widget>[
//            TodoTaskPage(), // 写待办问任务的类
//            HistoryTaskPage(),
//            FinishTaskPage(),
//            LaunchTaskPage(),
//            Container(
////              width: 120,
////              height: 50,
////              color: Colors.green,
//              child: ListView(
//                children: <Widget>[
//                  Text("待审核的订单"),
//                ],
//              ),
//            ),

//          ],
        ),
      ),
    );
  }

  /**
   * tab 的集合
   */
  List<Widget> setTabWidget() {
    List<Widget> list = new List();
    for (var i = 0; i < tabList.length; i++) {
      print("....标题:${tabList[i]}");
      Tab tab = new Tab(
        text: tabList[i],
      );
      list.add(tab);
    }
    return list;
  }

  /**
   * 各个tab的详情
   */
  List<Widget> setContentViewWidget() {
    List<Widget> list = new List();
    for (var i = 0; i < tabList.length; i++) {
//      list.add(Container(
//        child: Text('家活动时间返回$i'),
//      ));
      var name = tabList[i];
      if (name != null) {
        if (name == "待办任务") {
          list.add(TodoTaskPage()); // 写待办问任务的类
        }else if(name == "历史任务"){
          list.add(HistoryTaskPage());
        }else if(name == "办结任务"){
          list.add(FinishTaskPage());
        }else if(name == "我发起的"){
          list.add(LaunchTaskPage());
        }else{
          list.add(Container(
            child: Text('返回了新的页面$i'),
          ));
        }
      }
    }
    return list;
  }

  /**
   * 接口获取数据
   */
  initHttpData() async {
    String apiUrlhttp = GlobalUrl.LISTPERMISSION;
    var map = {
      "": "",
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };
    HttpUtil.get(apiUrlhttp, data: map, headers: mapHeaders, success: (data) {
      var success = data["success"];
//      LogUtil.v("success:$success");
      var message = data["msg"];
      var body = data["data"];
      var code = data["code"];
//      LogUtil.v("body:$body");
      if (success != null && success == true) {
        LogUtil.v("进来了");
        List menuList = body["menuList"];
//        LogUtil.v("menuList:menuList");
        LogUtil.v(menuList.length);

        setState(() {
          dataList = menuList;
        });

        for (var i = 0; i < menuList.length; i++) {
          var miName = menuList[i]["miName"];
          LogUtil.v("一级数据miName:$miName");
//          tabList.add(miName); // 一级数据
          if (miName != null && miName == "待办管理") { // 添加待办管理的数据
            List children = menuList[i]["children"];
            for (var j = 0; j < children.length; j++) {
              var name = children[j]["miName"];
//
              tabList.add(name); // 一级数据
              LogUtil.v("二级数据name:$name");
            }
          }

          List children = menuList[i]["children"];
          if (children != null) {
//            for (var i = 0; i < children.length; i++) {
//              var name = children[i]["miName"];
//              LogUtil.v("name:$name");
//            }
          }
        }

        setState(() {
          tabList = tabList;
        });
      } else {
        if (message != null) {
          ToastUtils.toast(message);
        }
        if (code == "401") {
          //用户登录超时
          print("超时了啊");
          Storage.clear(); // 清除数据
          //跳转并关闭当前页面
          Navigator.pushAndRemoveUntil(
            context,
            new MaterialPageRoute(builder: (context) => new LoginPage()),
            (route) => route == null,
          );
        }
      }
    }, error: (errorMsg) {});
  }
}
